<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\lib\SuPengJun;
use app\api\service\DynamicService;
use app\api\service\GoodsService;
use app\common\model\dynamic\DynamicModel;
use app\common\model\goods\GoodsClassifyModel;
use app\common\model\goods\GoodsModel;
use app\common\model\goods\GoodsProductModel;
use app\common\model\order\OrderGoodsModel;
use app\common\model\user\UserCartModel;
use app\common\model\user\UserModel;
use think\facade\Db;
use think\Request;

class Goods extends Controller
{
    protected array $middleware = [
        'api' => ['except' => ['list', 'details']],
        'orCheck' => ['only' => ['list', 'details']]
    ];

    /**
     * 商品列表
     */
    public function list(Request $request)
    {
        $classifyId = $request->get('classify_id', 0);
        $classifyType = $request->get('classify_type', 0);
        $condition[] = ['status', '=', 1];
        $whereRaw = [];
        if ($classifyId) {
            if ($classifyType != 1) {
                $classifyIds = GoodsClassifyModel::where('classify_id', $classifyId)->column('id');
                array_unshift($classifyIds, $classifyId);
                $findSetSql = [];
                foreach ($classifyIds as $id) {
                    $findSetSql[] = "FIND_IN_SET($id, classify_ids)";
                }
                $whereRaw = implode(' OR ', $findSetSql);
            } else {
                $condition[] = ['classify_ids', 'find in set', $classifyId];
            }
        }
        $data = GoodsModel::where($condition)
            ->where($whereRaw)
            ->field(GoodsService::goods_find())
            ->order(['weigh' => 'desc', 'id' => 'desc'])
            ->paginate(12);
        $data->map(function ($v) {
            $v['browse'] = SuPengJun::convert($v['browse']);
            $v['product'] = GoodsProductModel::where('goods_id', $v['id'])->where('status', 1)
                ->order(['weigh' => 'desc', 'id' => 'desc', 'stock' => 'desc'])
                ->field('price,line_price')->find();
            $v['product']['line_price'] = SuPengJun::formatPrice($v['product']['line_price']);
            return $v;
        });
        return success('success', $data);
    }

    /**
     * 商品详情
     * @param array $id 商品ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function details(Request $request)
    {
        $uid = $request->uid;
        $id = $request->get('id');
        $data = GoodsModel::where('id', $id)->where('status', 1)
            ->field(GoodsService::goods_find(1))
            ->find();
        if (!$data) return error('未找到商品或商品已下架，请稍后重试！');
        $data['product'] = GoodsProductModel::where('goods_id', $id)->where('status', 1)
            ->order(['weigh' => 'desc', 'id' => 'desc', 'stock' => 'desc'])
            ->field('id,price,line_price,img,name,stock')->select();
        $orderIds = OrderGoodsModel::where('goods_id', $id)->distinct(true)->column('order_id');
        $data['comment'] = DynamicModel::whereIn('order_id', $orderIds)->whereIn('status', [2, 3])->count();
        if ($data['comment']) {
            $uids = DynamicModel::whereIn('order_id', $orderIds)->orderRaw('RAND()')->limit(4)->column('user_id');
            $data['comment_user'] = UserModel::whereIn('id', $uids)->column('avatar');
        }
        $data['cart_count'] = UserCartModel::where('status', 1)->where('user_id', $uid)->count();
        GoodsModel::where('id', $id)->update(['browse' => new \think\db\Raw('browse+1')]);
        return success('success', $data);
    }

    /**
     * 获取商品关联的动态内容列表
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function dynamic(Request $request)
    {
        $uid = $request->uid;
        $id = $request->get('id', 0);
        $condition[] = ['status', 'in', [2, 3]];
        $orderIds = OrderGoodsModel::where('goods_id', $id)->where('status', 1)->distinct(true)->column('order_id');
        $condition[] = ['order_id', 'in', $orderIds];
        $data = DynamicModel::where($condition)
            ->order(['status' => 'asc', 'id' => 'desc'])
            ->field(DynamicService::dynamic_find())
            ->paginate(8);
        $data = DynamicService::dynamic_map($data, $uid, 1);
        DynamicModel::whereIn('id', $data->column('id'))->update(['browse' => new \think\db\Raw('browse+1')]);
        return success('success', $data);
    }

    /**
     * 规格列表
     * @param array $id 规格ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function product(Request $request)
    {
        $id = $request->get('id');
        $data = GoodsProductModel::where('goods_id', $id)->where('status', 1)
            ->order(['weigh' => 'desc', 'id' => 'desc', 'stock' => 'desc'])
            ->field('id,price,line_price,img,name,stock')->select();
        return success('success', $data);
    }

    /**
     * 加入购物车
     * @param array $goodsId 商品ID
     * @param array $goodsProductId 规格ID
     * @param array $quantity 数量
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function add_cart(Request $request)
    {
        $uid = $request->uid;
        $goodsId = $request->post('goods_id');
        $goodsProductId = $request->post('goods_product_id');
        $quantity = $request->post('quantity');
        $cartQuantity = UserCartModel::where('user_id', $uid)->where('goods_product_id', $goodsProductId)->value('quantity');
        if ($cartQuantity) {
            UserCartModel::where('user_id', $uid)->where('goods_product_id', $goodsProductId)
                ->update(['quantity' => $cartQuantity + $quantity]);
        } else {
            (new UserCartModel())->save([
                'goods_id' => $goodsId,
                'goods_product_id' => $goodsProductId,
                'quantity' => $quantity,
                'user_id' => $uid,
                'create_time' => time()
            ]);
        }
        GoodsModel::where('id', $goodsId)->inc('cart', (int)$quantity)->save();
        return success('success');
    }

    /**
     * 购物车列表
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function cart_list(Request $request)
    {
        $uid = $request->uid;
        if (GoodsService::handle_cart($uid)) {
            $data = UserCartModel::where('user_id', $uid)
                ->order(['status' => 'asc', 'id' => 'desc'])
                ->field('id,goods_id,goods_product_id,quantity,check,status')
                ->select();
            $data->map(function ($v) {
                $v['product'] = GoodsProductModel::where('id', $v['goods_product_id'])->field('id,price,line_price,img,name,stock')->find();
                $v['goods_name'] = GoodsModel::where('id', $v['goods_id'])->value('name');
                $v['status_str'] = GoodsService::cart_status($v['status']);
                $v['is_quantity'] = false;
                return $v;
            });
            return success('success', $data);
        }
    }

    /**
     * 保存选中状态
     * @param array $type 保存类型:1=单选选中状态,2=全选,3=修改数量,4=修改规格
     * @param array $id 购物车ID
     * @param array $check 当前选中状态:0=未选中,1=选中，type=1和2和时候必填
     * @param array $quantity 数量，type=3和4的时候必填
     * @param array $gpId 规格ID，type=4时必填
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function save_cart(Request $request)
    {
        $uid = $request->uid;
        $type = $request->post('type', 0);
        $id = $request->post('id', 0);
        $check = $request->post('check', 0);
        $quantity = $request->post('quantity', 0);
        $gpId = $request->post('goods_product_id', 0);
        $condition[] = ['user_id', '=', $uid];
        if ($type == 1) {
            $condition[] = ['id', '=', $id];
            UserCartModel::where($condition)->update(['check' => $check == 1 ? 0 : 1]);
        } else if ($type == 2) {
            UserCartModel::where($condition)->update(['check' => $check == 1 ? 0 : 1]);
        } else if ($type == 3) {
            $condition[] = ['id', '=', $id];
            UserCartModel::where($condition)->update(['quantity' => $quantity]);
        } else if ($type == 4) {
            $ucQuantity = UserCartModel::where($condition)->where('goods_product_id', $gpId)->value('quantity');
            $goodsQuantity = GoodsProductModel::where('id', $gpId)->value('stock');
            if ($ucQuantity) {
                $quantity = $ucQuantity + $quantity;
                UserCartModel::where($condition)->where('goods_product_id', $gpId)
                    ->update(['quantity' => $quantity > $goodsQuantity ? $goodsQuantity : $quantity]);
                UserCartModel::where($condition)->where('id', $id)->delete();
            } else {
                UserCartModel::where($condition)->where('id', $id)
                    ->update([
                        'goods_product_id' => $gpId,
                        'quantity' => $quantity > $goodsQuantity ? $goodsQuantity : $quantity
                    ]);
            }
        }
        return success('success');
    }

    /**
     * 删除购物车商品
     * @param array $id 购物车ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function cart_del(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id', 0);
        $userCart = UserCartModel::where('id', $id)->where('user_id', $uid)->field('id,quantity,user_id,goods_id')->find();
        $userCart->delete();
        GoodsModel::where('id', $userCart['goods_id'])->dec('cart', $userCart['quantity'])->save();
        return success('success');
    }
}
